// 用于通信和部分宏定义

#ifndef _COMMUNICATION_H_
#define _COMMUNICATION_H_

#include "chess_pieces.h"
#include "base_struct.h"
#include <iostream>
#include <unistd.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <error.h>

#define syserr(err)  \
    do               \
    {                \
        perror(err); \
        exit(-1);    \
    } while (0)

typedef struct _Change_
{
    ChessInfo chess;
    Position target_pos;
} Change;

enum CmdType
{
    ChangeChess = 0,
    Cat_effectively,
    Cat_uneffectively,
    Red_cmd,
    Black_cmd,
    Win,
    Fail
};

typedef struct _ComData
{
    int type_cmd;
    Change change;
} ComData;

// 获取监听套接字，发送错误直接打印错误信息 关闭进程
int getListen(const char *ip, const short port);

class Client
{
private:
    int socket_com;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    socklen_t socklen;
    char *data = nullptr;
    unsigned int data_len = 0;
    unsigned int data_size = 0;

    std::string error_message;

public:
    Client(int sockfd);

    std::string getErrorMessage();
    void *readClinet(unsigned int datalen);
    void writeClinet(const void *data, unsigned int datalen);
    int getSocketCom() { return socket_com; };

    ~Client()
    {
        close(socket_com);
        free(data);
    };
};

#endif
//_COMMUNICATION_H_